<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="vscode 远程调试 linux 上的 python 代码, 湮灭星空,博客,Python,后端">
    <meta name="description" content="基本原理
微软为 python远程调试提供了一个叫做ptvsd的库，可以在这里获取。ptvsd作为一个debug server嵌入到目标 python进程中，然后使用 vscode作为debugger，主动连接到debug server上。">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>vscode 远程调试 linux 上的 python 代码 | 湮灭星空</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<link rel="alternate" href="/atom.xml" title="湮灭星空" type="application/atom+xml">
</head>

<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper head-container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">湮灭星空</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友链</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">湮灭星空</div>
        <div class="logo-desc">
            
            天下寥寥，苍生涂涂，诸子百家，唯我纵横
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友链
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/23.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        vscode 远程调试 linux 上的 python 代码
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/markdown/">
                                <span class="chip bg-color">markdown</span>
                            </a>
                        
                            <a href="/tags/linux/">
                                <span class="chip bg-color">linux</span>
                            </a>
                        
                            <a href="/tags/python/">
                                <span class="chip bg-color">python</span>
                            </a>
                        
                            <a href="/tags/vscode/">
                                <span class="chip bg-color">vscode</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Tech/" class="post-category">
                                Tech
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2019-04-14
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2019-05-14
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    1.4k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    5 分
                </div>
                
				
                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
            
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="基本原理"><a class="header-anchor" href="#基本原理"></a>基本原理</h2>
<p>微软为 <code>python</code>远程调试提供了一个叫做<code>ptvsd</code>的库，可以在<a href="https://pypi.python.org/pypi/ptvsd" target="_blank" rel="noopener">这里</a>获取。<code>ptvsd</code>作为一个<code>debug server</code>嵌入到目标 <code>python</code>进程中，然后使用 <code>vscode</code>作为<code>debugger</code>，主动连接到<code>debug server</code>上。</p>
<p>只要我们配置了正确的 <code>site-package</code> 路径，让本地的 <code>vscode</code> 能把服务器上正在运行的代码和本地的代码配对，就可以开心的调试了，不仅可以调试自己的代码，还能调试标准库和第三方库。</p>
<p>这样子一来我们即使面对一个需要调试的集群，也可以轻松应对，和同事一起调试也不需要频繁重启目标进程修改代码了。</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-05-14-143936.jpg" alt="img"></p>
<h2 id="1-在-linux上的设置"><a class="header-anchor" href="#1-在-linux上的设置"></a>1. 在 <code>linux</code>上的设置</h2>
<p>以下两点必须满足：</p>
<ul>
<li>
<p>一台远程运行 <code>python</code>代码的 <code>linux</code>电脑</p>
</li>
<li>
<p>远程 <code>linux</code>主机的防火墙必须开放<code>5678</code>端口，该端口是用于进行远程调试的</p>
<blockquote>
<p>这个<code>5678</code>端口应该是固定的，是<code>ptvsd.enable_attach()</code>专门用来远程调试的。</p>
</blockquote>
</li>
</ul>
<h3 id="linux防火墙开放指定端口-5678"><a class="header-anchor" href="#linux防火墙开放指定端口-5678"></a><code>linux</code>防火墙开放指定端口（<code>5678</code>）</h3>
<p>由于我的服务器使用的os是<code>Ubuntu</code>，所以这里就介绍一下<code>Ubuntu</code>下的方法，其他<code>linux</code>应该也是大同小异，需要自己去尝试。</p>
<h3 id="安装iptables"><a class="header-anchor" href="#安装iptables"></a>安装iptables</h3>
<p>一般情况下，<code>ubuntu</code>安装好的时候，<code>iptables</code>会被安装上，如果没有的话那就安装上吧</p>
<ol>
<li>安装<br>
在终端输入</li>
</ol>
<pre><code>$ sudo apt-get install iptables
</code></pre>
<ol start="2">
<li>添加规则<br>
在终端输入</li>
</ol>
<pre><code>$ iptables -I INPUT -p tcp --dport 80 -j ACCEPT
</code></pre>
<p>中间的80为所需要开放的端口</p>
<ol start="3">
<li>保存规则<br>
在终端输入</li>
</ol>
<pre><code>$ iptables-save
</code></pre>
<p>完成上述命令我们就完成了开放指定的端口，但是如果此时服务器重启，上述规则就没有了，所以我们需要对规则进行一下持续化操作</p>
<h3 id="持续化规则"><a class="header-anchor" href="#持续化规则"></a>持续化规则</h3>
<p>这里我们需要在安装一下工具来帮我们实现，这里我们使用 <code>iptables-persistent</code></p>
<ol>
<li>安装<code>iptables-persistent</code></li>
</ol>
<pre><code>$ sudo apt-get install iptables-persistent
</code></pre>
<ol>
<li>持久化规则</li>
</ol>
<pre><code>$ sudo netfilter-persistent save
$ sudo netfilter-persistent reload
</code></pre>
<p>完成上述操作就可以永久打开我们需要的端口了</p>
<h2 id="2-准备好-python程序"><a class="header-anchor" href="#2-准备好-python程序"></a>2. 准备好 <code>python</code>程序</h2>
<ol>
<li>
<p>本次调试使用的是<code>flask</code>项目，<code>flask</code>的启动文件<code>fisher.py</code>内容如下：</p>
<pre><code class="language-python">from app import create_app


app = create_app()

if __name__ == &quot;__main__&quot;:
    app.run(host='0.0.0.0', port=8000, debug=app.config['DEBUG'], threaded=True)
</code></pre>
</li>
<li>
<p>安装用于远程调试的<code>ptvsd</code>库，使用如下命令安装：</p>
<pre><code>pip install ptvsd
</code></pre>
</li>
<li>
<p>需要在 <code>fisher.py</code>中添加如下代码才能启用远程调试，且必须放在文件的开头。这虽然不是一个严格的要求，但是如果在<code>enable_attach</code>被调用前就已经有进程启动了，那么这个进程是无法被调试的，所以最好确保<code>enable_attach</code>在进程被启动前调用。</p>
<pre><code class="language-python">import ptvsd
ptvsd.enable_attach()
</code></pre>
</li>
<li>
<p>修改后的<code>fisher.py</code>文件如下所示。</p>
<pre><code class="language-python">from app import create_app
import ptvsd

ptvsd.enable_attach()

app = create_app()

if __name__ == &quot;__main__&quot;:
    app.run(host='0.0.0.0', port=8000, debug=app.config['DEBUG'], threaded=True)
</code></pre>
<p>在终端，将目录切换到 <code>flask</code>项目的根目录，启动项目的虚拟环境，使用如下命令启动 <code>python</code>程序：</p>
<pre><code>python fisher.py
</code></pre>
<p>这样做是为了确保<code>enable_attach</code>已经被调用，等待远程调试的接入。</p>
<blockquote>
<p>这样启动 <code>flask</code>应用后可以使用，<code>nginx</code>设置好的域名访问网站进行调试。之前部署的时候是使用 <code>nginx</code>+<code>gunicorn</code>+<code>flask</code>部署的，进行远程调试的时候则需要关闭 <code>gunicorn</code></p>
</blockquote>
</li>
</ol>
<h2 id="3-使用-python工具连接到远程-linux主机"><a class="header-anchor" href="#3-使用-python工具连接到远程-linux主机"></a>3. 使用 <code>python</code>工具连接到远程 <code>linux</code>主机</h2>
<h3 id="安装插件"><a class="header-anchor" href="#安装插件"></a>安装插件</h3>
<p>在进行所有步骤之前，我们需要装两个插件：</p>
<ul>
<li><code>python</code>插件：该插件可以用于远程调试<br>
<img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-05-14-143940.jpg" alt="image-20181018191230145"></li>
<li><code>ftp_sync</code>插件：该插件是文件同步工具，用于本地文件与远程主机的文件同步<br>
<img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-05-14-143941.jpg" alt=""></li>
</ul>
<h3 id="配置调试的启动文件"><a class="header-anchor" href="#配置调试的启动文件"></a>配置调试的启动文件</h3>
<ol>
<li>
<p>将远程项目从远程主机上下载下来，不管项目放在本地的什么位置，只要保证项目的根目录文件名相同即可。打开命令面板，使用如下命令下载：</p>
<pre><code>ftp-sync:Remote to Local
</code></pre>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-05-14-143943.jpg" alt="image-20181018191556590"></p>
</li>
<li>
<p>（可选操作）你可以在本地项目的虚拟环境中安装<code>ptvsd</code>库。</p>
</li>
<li>
<p>配置调试的启动文件<code>launch.json</code>，改启动文件路径为<code>.vscode/launch.json</code>，编辑启动文件如下：</p>
<pre><code class="language-json">{
    &quot;version&quot;: &quot;0.2.0&quot;,
    &quot;configurations&quot;: [

        {
            &quot;name&quot;: &quot;Attach (Remote Debug)&quot;,
            &quot;type&quot;: &quot;python&quot;,
            &quot;request&quot;: &quot;attach&quot;,
            &quot;port&quot;: 5678,
            &quot;host&quot;: &quot;111.231.55.212&quot;,
            &quot;localRoot&quot;: &quot;/Users/stefanannihilater/PycharmProjects/fisher&quot;,
            &quot;remoteRoot&quot;: &quot;/home/ubuntu/web_site/fisher&quot;
        },
    ]
}
</code></pre>
<p>参数解释：</p>
<p><code>name</code>：调试配置的名称，这个随意写</p>
<p><code>type</code>：语言类型，本次是 <code>python</code></p>
<p><code>request</code>：<code>request</code>参数的取值有两种<code>launch</code>和 <code>attach</code>。</p>
<ul>
<li><code>launch</code>模式：由 <code>vscode</code>来启动一个独立的具有 <code>debug</code>模式的程序</li>
<li><code>attach</code>模式：附加于（或者说监听）一个<strong>已启动的程序</strong>（改程序必须开启 debug 模式）</li>
</ul>
<p><code>port</code>：远程 <code>linux</code>主机的端口</p>
<p><code>host</code>：远程 <code>linux</code>主机的地址</p>
<p><code>localRoot</code>：本地项目根目录的路径</p>
<p><code>remoteRoot</code>：远程主机项目根目录的绝对路径</p>
</li>
<li>
<p>随意在你想设置的地方设置断点</p>
</li>
<li>
<p>选择刚刚设置好的远程调试模式，点击启动，完美启动远程调试<br>
<img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-05-14-143945.jpg" alt="image-20181018193238535"></p>
</li>
</ol>
<p><a href="https://docs.microsoft.com/en-us/visualstudio/python/debugging-python-code-on-remote-linux-machines?view=vs-2017" target="_blank" rel="noopener">参考链接1</a>：<a href="https://docs.microsoft.com/en-us/visualstudio/python/debugging-python-code-on-remote-linux-machines?view=vs-2017" target="_blank" rel="noopener">https://docs.microsoft.com/en-us/visualstudio/python/debugging-python-code-on-remote-linux-machines?view=vs-2017</a></p>
<p><a href="https://www.jianshu.com/p/2ec5d16db02b" target="_blank" rel="noopener">参考链接2</a>：<a href="https://www.jianshu.com/p/2ec5d16db02b" target="_blank" rel="noopener">https://www.jianshu.com/p/2ec5d16db02b</a></p>
<p><a href="https://blog.jamespan.me/2016/06/09/remote-debug-your-python-code" target="_blank" rel="noopener">参考链接3</a>：<a href="https://blog.jamespan.me/2016/06/09/remote-debug-your-python-code" target="_blank" rel="noopener">https://blog.jamespan.me/2016/06/09/remote-debug-your-python-code</a></p>
<p><a href="https://github.com/Microsoft/ptvsd" target="_blank" rel="noopener">更多 ptvsd 用法在 github</a>：<a href="https://github.com/Microsoft/ptvsd" target="_blank" rel="noopener">https://github.com/Microsoft/ptvsd</a></p>

<div id="gitalk-container"></div>
<script src="https://cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script><link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css"><script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>

		<script>
		var gitalkConfig = {"clientID":"9eb5bc3ac1e1ff3ddac0","clientSecret":"4b7ae28042282281295075c2bf0c97ff1791cfeb","repo":"HexoBlogComments","owner":"Annihilater","admin":["Annihilater"],"distractionFreeMode":false};
	    gitalkConfig.id = md5(location.pathname);
		var gitalk = new Gitalk(gitalkConfig);
	    gitalk.render("gitalk-container");
	    </script>
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.klause.cn" rel="external nofollow noreferrer">湮灭星空</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.klause.cn/2019/04/14/markdown/vscode-yuan-cheng-diao-shi-linux-shang-de-python-dai-ma/">https://www.klause.cn/2019/04/14/markdown/vscode-yuan-cheng-diao-shi-linux-shang-de-python-dai-ma/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="https://www.klause.cn" target="_blank">湮灭星空</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/markdown/">
                                    <span class="chip bg-color">markdown</span>
                                </a>
                            
                                <a href="/tags/linux/">
                                    <span class="chip bg-color">linux</span>
                                </a>
                            
                                <a href="/tags/python/">
                                    <span class="chip bg-color">python</span>
                                </a>
                            
                                <a href="/tags/vscode/">
                                    <span class="chip bg-color">vscode</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
        </div>
    </div>

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2019/04/14/markdown/python-shi-jian-ri-qi-shi-jian-chuo-hu-zhuan/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/10.jpg" class="responsive-img" alt="Python 时间日期、时间戳互转">
                        
                        <span class="card-title">Python 时间日期、时间戳互转</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            1. 加载时间模块
In [1]: import time

2. 当前时间戳
In [2]: print(time.time())
1547028969.732987

3. 时间戳转日期
In [3]: x = time.localti
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2019-04-14
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Tech/" class="post-category">
                                    Tech
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/markdown/">
                        <span class="chip bg-color">markdown</span>
                    </a>
                    
                    <a href="/tags/python/">
                        <span class="chip bg-color">python</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2019/04/14/imooc/di-3-zhang-django-ji-chu/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/12.jpg" class="responsive-img" alt="第3章 Django 基础">
                        
                        <span class="card-title">第3章 Django 基础</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            3-2 配置表单页面试看
settings 配置

添加 apps 文件夹路径
配置数据库
配置模板文件路径
配置静态文件路由和静态文件路径（static_url 和 staticfiles_dirs）

数据库

migrations： 
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2019-04-14
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/imooc/" class="post-category">
                                    imooc
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/django/">
                        <span class="chip bg-color">django</span>
                    </a>
                    
                    <a href="/tags/xadmin/">
                        <span class="chip bg-color">xadmin</span>
                    </a>
                    
                    <a href="/tags/python/">
                        <span class="chip bg-color">python</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>

    
<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>

    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>



    <footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">年份</span>
            <a href="https://www.klause.cn" target="_blank">湮灭星空</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">199.2k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    window.setTimeout("siteTime()", 1000);
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2019";
                    var startMonth = "6";
                    var startDate = "28";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
            <span id="icp"><img src="/medias/icp.png" style="vertical-align: text-bottom;" />
                <a href="http://www.beian.miit.gov.cn" target="_blank">皖ICP备18005729号-1</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/Annihilater" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:yanmiexingkong@gmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>





    <a href="https://twitter.com/" class="tooltipped" target="_blank" data-tooltip="关注我的Twitter: https://twitter.com/" data-position="top" data-delay="50">
        <i class="fab fa-twitter"></i>
    </a>







    <a href="https://www.zhihu.com/" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>

    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
